package com.wswy.wzcx.ui.weather

import android.os.Bundle
import android.support.constraint.ConstraintSet
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.text.format.DateFormat
import android.text.style.RelativeSizeSpan
import android.text.style.SuperscriptSpan
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.blankj.utilcode.util.SizeUtils
import com.check.ox.sdk.LionWallView
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder
import com.facebook.drawee.span.DraweeSpan
import com.facebook.drawee.span.DraweeSpanStringBuilder
import com.facebook.drawee.span.SimpleDraweeSpanTextView
import com.wswy.wzcx.BuildConfig
import com.wswy.wzcx.R
import com.wswy.wzcx.api.Configs
import com.wswy.wzcx.model.weather.ForecastWeather
import com.wswy.wzcx.model.weather.WeatherData
import com.wswy.wzcx.module.RuntimeContext
import com.wswy.wzcx.module.base.CBaseFragment
import com.wswy.wzcx.module.weather.AmapWeatherManager
import com.wswy.wzcx.module.weather.WeatherUtils
import com.wswy.wzcx.utils.LunarCalender
import com.wswy.wzcx.utils.UiUtils
import kotlinx.android.synthetic.main.fragment_weather.*
import java.util.*

class WeatherFragment : CBaseFragment() {

    override fun getContentLayoutId(): Int {
        return R.layout.fragment_weather
    }


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        AmapWeatherManager.getWeatherLiveData().value?.run {
            bindWeather(this)


            //if (RuntimeContext.isPaidChannel()){
                showAd()
            //}
        }
    }

    private fun showAd(){
        if (TextUtils.isEmpty(BuildConfig.TUIA_APPKEY)){
            return
        }
        LayoutInflater.from(requireContext()).inflate(R.layout.ad_view_tui, null)?.let {


            it.id = R.id.id_tuia_ad


            root_content.addView(it, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
            val constraintSet = ConstraintSet()
            constraintSet.clone(root_content)
            constraintSet.connect(R.id.id_tuia_ad,ConstraintSet.RIGHT, ConstraintSet.PARENT_ID, ConstraintSet.RIGHT)
            constraintSet.connect(R.id.id_tuia_ad,ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP)
            constraintSet.setMargin(R.id.id_tuia_ad, ConstraintSet.TOP, SizeUtils.dp2px(30f))
            constraintSet.setMargin(R.id.id_tuia_ad, ConstraintSet.RIGHT, SizeUtils.dp2px(10f))
            constraintSet.applyTo(root_content)

            it.findViewById<LionWallView>(R.id.TMAw1)?.loadAd(Configs.TUIA_WEB_FLOAT)

        }
    }

    private fun bindWeather(weatherData: WeatherData){

        weatherData.forecastResult?.run {
            showForecast(this)
        }
//        view_root.setScrollableViewHelper(NestedScrollableViewHelper())
//
//        NewsController(tabLayout,indicator,vp_news).load(supportFragmentManager)

        weatherData.liveWeather?.run {

            tv_tips.text = WeatherUtils.getWeatherTips(weather)

            val now = Date()

            showDate(if (now.after(reportTime)) now else reportTime,weather)

            tv_humidity.text = getString(R.string.weather_info_humidity,humidity)
            tv_wind.text = getString(R.string.weather_info_wind,windDirection,windPower)

            tv_wash_car.text = weatherData.washCarDesc

            SpannableStringBuilder().run {

                append(temperature)

                append(SpannableString(getString(R.string.temperature_symbol)).apply {
                    setSpan(SuperscriptSpan(),0,length, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                    setSpan(RelativeSizeSpan(0.26667f),0,length, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                })

                tv_temp.text =this
            }


        }


    }


    private fun showDate(date: Date, weather:String?){
        LunarCalender().run {

            setDate(date)

            tv_yang_time.text = "${DateFormat.format("MM月dd日",date)}  $week  $weather"

            tv_nong_time.text = "${chineseMonth}${chineseDay} ${chineseYear}年"

        }
    }


    private fun showForecast(list : List<ForecastWeather>){

        list.getOrNull(0)?.run {
            tv_today_weather.text = "今天 · $dayWeather"

            setWeatherIcon(tv_today_temperature,this)

        }

        list.getOrNull(1)?.run {
            tv_tomorrow_weather.text = "明天 · $dayWeather"

            setWeatherIcon(tv_tomorrow_temperature,this)

        }

        list.getOrNull(2)?.run {

            val week = LunarCalender().run {
                setDate(date)
                week
            }

            tv_after_tomorrow_weather.text = "$week · $dayWeather"

            setWeatherIcon(tv_after_tomorrow_temperature,this)

        }

    }

    private fun setWeatherIcon(tv: SimpleDraweeSpanTextView, forecastWeather: ForecastWeather){
        tv.setDraweeSpanStringBuilder(DraweeSpanStringBuilder(getString(R.string.weather_forecast_temperature,forecastWeather.nightTemp,forecastWeather.dayTemp)).apply {

            val draweeHierarchy = GenericDraweeHierarchyBuilder.newInstance(resources)
                    .build()

            val controller = Fresco.newDraweeControllerBuilder()
                    .setUri(WeatherUtils.getWeatherIconUri(forecastWeather.dayWeather,true))
                    .build()

            setImageSpan(tv.context,draweeHierarchy,controller,0, SizeUtils.dp2px(24f), SizeUtils.dp2px(24f),false, DraweeSpan.ALIGN_CENTER)
        })
    }


}